<template>
  <view :style="customStyle" class="countdown">
    {{ timeText }}
  </view>
</template>

<script>
export default {
   name: "Timer", // 组件名称
  props: {
    targetTime: [String, Number], // 传入时间戳或 'Y-m-d H:i:s' 格式的时间
    format: {
      type: String,
      default: 'HH:mm:ss' // 默认格式
    },
    customStyle: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      timeText: '',
      timer: null
    };
  },
  computed: {
    endTime() {
      if (typeof this.targetTime === 'number') {
        return this.targetTime;
      } else {
        return new Date(this.targetTime.replace(/-/g, '/')).getTime();
      }
    }
  },
  methods: {
    startCountdown() {
      if (!this.endTime) return;
      
      this.updateTime();
      this.timer = setInterval(this.updateTime, 1000);
    },
    updateTime() {
      const now = new Date().getTime();
      const diff = this.endTime - now;
      
      if (diff <= 0) {
        this.timeText = '00:00:00';
        clearInterval(this.timer);
        return;
      }
      
      const hours = String(Math.floor((diff / (1000 * 60 * 60)) % 24)).padStart(2, '0');
      const minutes = String(Math.floor((diff / (1000 * 60)) % 60)).padStart(2, '0');
      const seconds = String(Math.floor((diff / 1000) % 60)).padStart(2, '0');
      
      this.timeText = this.format.replace('HH', hours).replace('mm', minutes).replace('ss', seconds);
    }
  },
  mounted() {
    this.startCountdown();
  },
  beforeDestroy() {
    clearInterval(this.timer);
  }
};
</script>

<style scoped>
.countdown {
  font-size: 16px;
  color: #333;
  text-align: center;
  padding: 5px 10px;
  border-radius: 5px;
  background-color: #f5f5f5;
}
</style>
